/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2025-06-28
 * Time: 19:45
 */
public class test6 {
    private static final int MAX_COUNT = 9;
    private static int currentNumber = 1;
    private static final Object lock = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(() ->{
            while (true) {
                synchronized (lock) {
                    while (currentNumber <= MAX_COUNT && currentNumber % 3 != 1) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (currentNumber > MAX_COUNT) {
                        break;
                    }
                    System.out.println("Thread 1: " + currentNumber);
                    currentNumber++;
                    lock.notifyAll();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    while (currentNumber <= MAX_COUNT && currentNumber % 3 != 2) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (currentNumber > MAX_COUNT) {
                        break;
                    }
                    System.out.println("Thread 2: " + currentNumber);
                    currentNumber++;
                    lock.notifyAll();
                }
            }
        });

        Thread t3 = new Thread(() -> {
            while (true) {
                synchronized (lock) {
                    while (currentNumber <= MAX_COUNT && currentNumber % 3 != 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (currentNumber > MAX_COUNT) {
                        break;
                    }
                    System.out.println("Thread 3: " + currentNumber);
                    currentNumber++;
                    lock.notifyAll();
                }
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
